package com.qfmy.web.app.service.impl.conmon;


import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.SearchLog;
import com.qfmy.web.app.mapper.common.SearchLogMapper;
import com.qfmy.web.app.service.conmon.SearchLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.novel
 * @date 2025/11/02
 * @description 搜索记录
 */
@Slf4j
@Service
public class SearchLogServiceImpl implements SearchLogService {

    /**
     * 注入搜索mapper
     */
    @Autowired
    private SearchLogMapper searchLogMapper;


    /**
     * 添加搜索
     * @param keyword
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSearchLog(String keyword) {
        //获取当前用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登入
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        //获取用户id
        Long userId = loginUser.getUserId();
        try {
            // 过滤无效关键词（如空字符串、长度过长）
            if (keyword == null || keyword.trim().isEmpty() || keyword.length() > 10) {
                return;
            }
           //根据用户id 和 关键词 查询搜索日志
            SearchLog log = searchLogMapper.selectByUserIdAndKeyword(userId, keyword);
            if (log == null) {
                // 保存到数据库
                log = new SearchLog();
                log.setKeyword(keyword.trim());
                log.setUserId(userId);
                log.setSearchTime(LocalDateTime.now());
                searchLogMapper.insert(log);
            }else{
                //更新搜索时间
                searchLogMapper.updateSearchTime(userId, keyword,LocalDateTime.now());
            }
        } catch (Exception e) {
            log.error("异步记录搜索日志失败", e);
        }

    }
}
